package com.guaoran.algorithm.queue;

import java.util.Stack;

/**
 * @Auth gucheng
 * @Desc 通过栈实现队列
 * @Date 2020/12/25 下午6:43
 */
public class ImplementQueueByStack {
    public static void main(String[] args) {
        ImplementQueueByStack myQueue = new ImplementQueueByStack();
        myQueue.push(1); // queue is: [1]
        myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
        System.out.println(myQueue.peek());
        System.out.println(myQueue.pop());
        System.out.println(myQueue.empty());
    }
    Stack<Integer> stack;
    Stack<Integer> stack2;

    /** Initialize your data structure here. */
    public ImplementQueueByStack() {
        stack = new Stack<>();
        stack2 = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(empty()){
            return -1;
        }

        if (stack2.isEmpty()) {
            while(!stack.isEmpty()) {
                stack2.push(stack.pop());
            }
        }
        return  stack2.pop();
    }

    /** Get the front element. */
    public int peek() {
        if(empty()){
            return -1;
        }
        if(stack2.isEmpty()){
            while (!stack.isEmpty()){
                stack2.push(stack.pop());
            }
        }
        return stack2.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack.isEmpty() && stack2.isEmpty();
    }
}
